package org.piaohao.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.piaohao.model.DocAcc;
import org.piaohao.model.Document;
import org.piaohao.model.Organization;
import org.piaohao.util.string.JsonUtil;
import org.piaohao.util.string.UUIDGenerator;

/**
 * Created on : 2013-5-10, 10:23:24
 *
 * @author piaohao
 */
public class DocController extends Controller {

    public static final String moduleName = "文件管理模块";

    public void index() {
        List<Organization> orgs = Organization.dao.find("select name,id from t_organization where id<>'0'");
        setAttr("orgs", orgs);
        render("/pages/document/document.jsp");
    }
    
    public void index2(){
         String para = getPara(0);
        int tab = 0;
        if (para != null && !para.equals("")) {
            tab = getParaToInt(0);
        }
        List<Organization> orgs = Organization.dao.find("select name,id from t_organization where id<>'0'");
        setAttr("tab", tab);
        setAttr("orgs", orgs);
        render("/pages/document/document.jsp");
    }

    public void list() {
        try {
            Integer start = getParaToInt("start");
            Integer limit = getParaToInt("limit");
            String orgId = (String) getSessionAttr("orgId");
            List<Document> documents = null;
            Long total = 0L;
            if (orgId.equals("0")) {
                documents = Document.dao.find("select * from t_document limit ?,?", start, limit);
                total = Db.queryLong("select count(*) from t_document");
            } else {
                documents = Document.dao.find("select * from t_document where org_id=? limit ?,?", orgId, start, limit);
                total = Db.queryLong("select count(*) from t_document where org_id=?", orgId);
            }
            renderJson(JsonUtil.printGrid(total, documents));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void listAcc() {
        try {
            Integer start = getParaToInt("start");
            Integer limit = getParaToInt("limit");
            String orgId = (String) getSessionAttr("orgId");
            List<Record> records = null;
            Long total = 0L;
            if (orgId.equals("0")) {
                records = Db.find("SELECT r2.id,r2.`name`,r2.`status`,t_organization.`name` `from`,r2.org_name \n"
                        + "from \n"
                        + "(SELECT r1.id,r1.`name`,r1.`status`,r1.`from`,t_organization.`name` org_name\n"
                        + "	from \n"
                        + "	(SELECT t_doc_acc.id,t_document.`name`,t_doc_acc.`status`,t_doc_acc.`from`,t_doc_acc.org_id\n"
                        + "		from \n"
                        + "		t_doc_acc LEFT JOIN t_document ON t_doc_acc.doc_id=t_document.id\n"
                        + "	) r1 \n"
                        + "	LEFT JOIN t_organization ON r1.org_id=t_organization.id\n"
                        + ") r2\n"
                        + "LEFT JOIN t_organization ON r2.`from`=t_organization.id");
                total = Db.queryLong("select count(*) from t_doc_acc");
            } else {
                records = Db.find("SELECT r2.id,r2.`name`,r2.`status`,t_organization.`name` `from`,r2.org_name \n"
                        + "from \n"
                        + "(SELECT r1.id,r1.`name`,r1.`status`,r1.`from`,t_organization.`name` org_name\n"
                        + "	from \n"
                        + "	(SELECT t_doc_acc.id,t_document.`name`,t_doc_acc.`status`,t_doc_acc.`from`,t_doc_acc.org_id\n"
                        + "		from \n"
                        + "		t_doc_acc LEFT JOIN t_document ON t_doc_acc.doc_id=t_document.id where t_doc_acc.org_id='" + orgId + "'\n"
                        + "	) r1 \n"
                        + "	LEFT JOIN t_organization ON r1.org_id=t_organization.id\n"
                        + ") r2\n"
                        + "LEFT JOIN t_organization ON r2.`from`=t_organization.id");
                total = Db.queryLong("select count(*) from t_doc_acc where org_id=?", orgId);
            }
            renderJson(JsonUtil.printGrid(total, records));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void accept() {
        try {
            String id = getPara("id");
            DocAcc da = DocAcc.dao.findById(id);
            da.set("status", "已接收");
            da.update();
            renderJson(JsonUtil.printSuccess(true, "成功"));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonUtil.printSuccess(false, "失败"));
        }
    }

    public void add() {
        try {
            Document document = getModel(Document.class);
            String[] tos = getParaValues("to");
            String to = "";
            for (int i = 0; i < tos.length; i++) {
                if (i != tos.length - 1) {
                    to += tos[i] + ",";
                } else {
                    to += tos[i];
                }
            }
            document.set("to", to);
            String para1 = getPara("publish_date");
            DateFormat df = new SimpleDateFormat("yy-MM-dd");
            Date pubDate = df.parse(para1);
            document.set("publish_date", new Timestamp(pubDate.getTime()));
            String id = UUIDGenerator.getUUID();
            if (document.getStr("id") == null || document.getStr("id").trim().equals("")) {
                document.set("id", id);
                document.save();
            }
            DocAcc da = new DocAcc();
            for (int i = 0; i < tos.length; i++) {
                da.set("id", UUIDGenerator.getUUID());
                da.set("doc_id", id);
                da.set("status", "未接收");
                da.set("from", document.getStr("org_id"));
                da.set("org_id", tos[i]);
                da.save();
            }
            renderJson(JsonUtil.printSuccess(true, "成功"));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonUtil.printSuccess(false, "失败"));
        }
    }

    public void update() {
        try {
            Document document = getModel(Document.class);
            document.update();
            renderJson(JsonUtil.printSuccess(true, "成功"));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonUtil.printSuccess(false, "失败"));
        }
    }

    public void delete() {
        try {
            String[] ids = getParaValues("ids");
            for (int i = 0; i < ids.length; i++) {
                Document.dao.deleteById(ids[i]);
            }
            renderJson(JsonUtil.printSuccess(true, "成功"));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonUtil.printSuccess(false, "失败"));
        }
    }

    public void deleteAcc() {
        try {
            String[] ids = getParaValues("ids");
            for (int i = 0; i < ids.length; i++) {
                DocAcc.dao.deleteById(ids[i]);
            }
            renderJson(JsonUtil.printSuccess(true, "成功"));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonUtil.printSuccess(false, "失败"));
        }
    }

    public void showDetail() {
        try {
            String id = getPara(0);
            Record document = Db.findFirst("select d.*,o.name orgName from t_document d left join t_organization o on d.org_id=o.id where d.id=?", id);
            String[] tos = Db.queryStr("select `to` from t_document where id=?", id).split(",");
            List<String> orgs = new ArrayList<String>();
            for (int i = 0; i < tos.length; i++) {
                String orgName = Db.queryStr("select name from t_organization where id=?", tos[i]);
                orgs.add(orgName);
            }
            setAttr("document", document);
            setAttr("orgs", orgs);
            render("/pages/document/detail.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            renderNull();
        }
    }

    public void showAccDetail() {
        try {
            String id = getPara(0);
            Record document = Db.findFirst("SELECT r2.id,r2.`name`,r2.`status`,t_organization.`name` `from`,r2.org_name ,r2.content\n"
                    + "from \n"
                    + "(SELECT r1.id,r1.`name`,r1.`status`,r1.`from`,t_organization.`name` org_name,r1.content\n"
                    + "	from \n"
                    + "	(SELECT t_doc_acc.id,t_document.`name`,t_doc_acc.`status`,t_doc_acc.`from`,t_doc_acc.org_id,t_document.content\n"
                    + "		from \n"
                    + "		t_doc_acc LEFT JOIN t_document ON t_doc_acc.doc_id=t_document.id where t_doc_acc.id=?\n"
                    + "	) r1 \n"
                    + "	LEFT JOIN t_organization ON r1.org_id=t_organization.id\n"
                    + ") r2\n"
                    + "LEFT JOIN t_organization ON r2.`from`=t_organization.id", id);
            setAttr("document", document);
            render("/pages/document/accDetail.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            renderNull();
        }
    }

    public void getDocById() {
        try {
            String id = getPara("docId");
            String content = Db.queryStr("select content from t_document where id=?", id);
            Map map = new HashMap();
            map.put("content", content);
            renderJson(JsonUtil.printSuccess(true, "成功", map));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(JsonUtil.printSuccess(false, "失败"));
        }
    }
}
